package java8.stream;

import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * @program: util
 * @description:
 * @author: zhouliangliang
 * @create: 2019-09-04 11:04
 **/
public class ParallelStream {

    public static long sequentialSum(long n) {
        return Stream.iterate(1l, i->i+1).limit(n).reduce(0l,Long::sum);
    }

    public static long parallelSum(long n) {
        return Stream.iterate(1l, i-> i+1).limit(n).parallel().reduce(0l, (a,b) -> a+b);
    }

    public static long forkJoinSum(long n) {
        long[] numbers = LongStream.rangeClosed(1, n).toArray();
        ForkJoinSumCalculator calculator = new ForkJoinSumCalculator(numbers);
        return new ForkJoinPool().invoke(calculator);
    }
}
